import { useState,useEffect } from 'react';
import { Table,Switch,Space,Button,Card,ConfigProvider,Modal,Form, Input,Checkbox,message,Popconfirm  } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import zh_CN from 'antd/es/locale/zh_CN';
import {getRoleListApi,editRoleApi,delRoleApi,addRoleApi,changeRoleStateApi} from '@/api/authority'

interface DataType {
  roleId:number;
  key:number;
  roleName: string;
  roleJob: string;
  roleNum: number;
  createTime: string;
  roleState:number;
  menuIds:{label:string,value:string}[]
  roleMenus?:[]
}

function RoleManagement() {
  const [roleList,setRoleList] = useState<DataType[]>([])
  const [selectedRow, setSelectedRow] = useState<DataType[]>([]);
  const [open, setOpen] = useState(false);
  const [openAdd,setOpenAdd] = useState(false)
  const [checkboxOptions, setCheckboxOptions] = useState([{
    label: 'Apple', value: 0 
  }]);
  const [editForm] = Form.useForm()
  const [addForm] = Form.useForm()
  //表格列
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'key',
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
    },
    {
      title: '职能描述',
      dataIndex: 'roleJob',
    },
    {
      title: '成员',
      dataIndex: 'roleNum',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '是否启用',
      dataIndex: 'roleState',
      render: (_, record) => {
        let state = false
        if(record.roleState === 1){
          state = true
        }
        return <Switch defaultChecked = {state} onChange={()=>{switchChange(record)}} />
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => (
        <Space size="middle">
          <Button className='edmit' onClick={()=>{editRole(record)}}>编辑</Button>
          <Popconfirm
            title="删除该角色"
            description="你真的要删除该角色嘛？"
            okText="删除"
            cancelText="取消"
            onConfirm={()=>{delRole(record)}}
          >
            <Button id='del'>删除</Button>
          </Popconfirm>
        </Space >
      ),
    },
  ];
  const [messageApi, contextHolder] = message.useMessage();
  useEffect(()=>{
    getRoleList()
  },[])

  //获取列表数据
  const getRoleList = async()=>{
    const {data:{menuListAll,roleMenus}} = await getRoleListApi()
    const allAuthority = menuListAll.filter((item:any)=>{
      if(item.pid === 0) return item
    })
    const checkArr =  allAuthority.map((item:any)=>{
      let obj = {
        label:'',
        value:0
      }
      obj.label = item.menuRemark
      obj.value = item.menuId
      return obj
    })
    setCheckboxOptions(checkArr)
    const roleMenusArr = roleMenus.map((item :any,index:number)=>{
      item.key = index+1
      return item
    })
    setRoleList(roleMenusArr)
  }
  //是否启用
  const switchChange = async(row:any)=>{
    let data = {
      roleId:row.roleId,
      state:0
    }
    if(row.roleState === 0){
      data.state = 1
    }
    await changeRoleStateApi(data)
    getRoleList()
  }
  //点击编辑按钮
  const editRole = (val:DataType)=>{
    let authorityArr = []
    if(val.roleMenus){
      let authority= val.roleMenus.filter((item:any)=>{
        if(item.pid === 0) return item
      })
      authorityArr = authority.map((item:any)=>{
        return item.menuId
      })
    }
    let obj = {
      roleId:0,
      roleName:'',
      roleJob:'',
      menuIds:['']
    }
    obj.roleId  = val.roleId
    obj.roleName = val.roleName
    obj.roleJob = val.roleJob
    obj.menuIds = authorityArr
    editForm.setFieldsValue(obj)
    setOpen(true);
  }
  //添加角色
  const addRole = async(val:any)=>{
    const res =await addRoleApi(val)
    if(~~res.code !== 200){
      messageApi.open({
      type: 'error',
      content: res.msg
      });
      return
    }else{
      getRoleList()
      messageApi.open({
        type: 'success',
        content: '添加角色成功！'
      });
      setOpenAdd(false)
    }
    
    
  }
  //删除角色
  const delRole = async(val:DataType)=>{
    const res = await delRoleApi([val.roleId])
    if(~~res.code !== 200){
      messageApi.open({
        type: 'error',
        content: res.msg
        });
        return
    }
    getRoleList()
    messageApi.open({
      type: 'success',
      content: '已删除该角色！'
    });
  }
  const rowSelection = {
    onChange:(key :any,row :DataType[])=>{
      setSelectedRow(row)
    },
  }
  //批量删除
  const delMore = async()=>{
    const idArr = selectedRow.map((item:DataType)=>item.roleId)
    const res = await delRoleApi(idArr)
    if(~~res.code !== 200){
      messageApi.open({
        type: 'error',
        content: res.msg
        });
        return
    }
    getRoleList()
    messageApi.open({
      type: 'success',
      content: '批量删除角色成功！'
    });
  }
  const handleOk = () => {
    editForm.submit()
  };
  const handleCancel = () => {
    setOpen(false);
  };
  //编辑表单提交
  const onFinish = async(val:any)=>{
    await editRoleApi(val)
    getRoleList()
    messageApi.open({
      type: 'success',
      content: '修改成功！',
    });
    setOpen(false);
  }

    return (
        <div className='RoleManagement'>
            <p className="head">角色管理</p>
            {contextHolder}
            <Card title="数据列表" type="inner" style={{ marginTop:'20px'}} extra={<Space>
              <Button onClick={()=>{setOpenAdd(true)}} className='add'>添加</Button>
              <Popconfirm
                title="批量删除角色"
                description="你确定要批量删除角色嘛？"
                okText="删除"
                cancelText="取消"
                onConfirm={delMore}
              >
                <Button id='del'>批量删除</Button>
          </Popconfirm>
            </Space>}>
            <ConfigProvider locale={zh_CN}>
              <Table columns={columns} rowSelection={rowSelection} dataSource={roleList} pagination={{ position: ['bottomCenter'],
              defaultPageSize: 2,
              pageSizeOptions: [2, 5, 10, 15],
              showQuickJumper: true,
              showSizeChanger: true, }}  />
              </ConfigProvider>
            </Card >
            <Modal
              title="编辑角色权限"
              open={open}
              onOk={handleOk}
              onCancel={handleCancel}
            >
               <Form
                    form = {editForm}
                    name="editForm"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ maxWidth: 600 }}
                    autoComplete="off"
                    onFinish={onFinish}
                  >
                    <Form.Item
                      label="角色id"
                      name="roleId"
                    >
                      <Input disabled />
                    </Form.Item>
                    <Form.Item
                      label="角色名称"
                      name="roleName"
                      rules={[{ required: true, message: '输入该角色名称' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="职能描述"
                      name="roleJob"
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="对应权限"
                      name="menuIds"
                      style={{height:'120px'}}
                    >
                      <Checkbox.Group
                        options={checkboxOptions}
                        style={{ display:'inline-block' }}
                      />
                    </Form.Item>
                  </Form>
            </Modal>
            <Modal
              title="添加角色"
              open={openAdd}
              onOk={()=>{addForm.submit()}}
              onCancel={()=>{setOpenAdd(false)}}
            >
               <Form
                    form = {addForm}
                    name="addForm"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    autoComplete="off"
                    onFinish={addRole}
                  >
                    <Form.Item
                      label="角色名称"
                      name="roleName"
                      rules={[{ required: true, message: '输入该角色名称' }]}
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="职能描述"
                      name="roleJob"
                    >
                      <Input />
                    </Form.Item>
                    <Form.Item
                      label="对应权限"
                      name="menuIds"
                      style={{height:'120px'}}
                    >
                      <Checkbox.Group
                        options={checkboxOptions}
                        style={{ display:'inline-block' }}
                      />
                    </Form.Item>
                  </Form>
            </Modal>
        </div>
    )
}

export default RoleManagement